package com.sangeng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.dto.AddUserDTO;
import com.sangeng.domain.dto.UserSearchParamsDTO;
import com.sangeng.domain.entity.user.LoginUser;
import com.sangeng.domain.entity.user.User;
import com.sangeng.domain.vo.PageUserInfoVO;
import com.sangeng.domain.vo.Result;
import com.sangeng.domain.vo.UserListVO;
import com.sangeng.mapper.UserMapper;
import com.sangeng.service.IRoleService;
import com.sangeng.service.IUserRoleService;
import com.sangeng.service.IUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private IUserRoleService userRoleService;
    @Resource
    private IRoleService roleService;

    /**
     * 添加用户
     */
    @Override
    @Transactional
    public Result<String> addUser(AddUserDTO addUserDTO){
        //用户名不能重复
        if(selectByUserName(addUserDTO.getUserName()) != null){
            return Result.fail("用户名已存在");
        }
        User user = BeanUtil.copyProperties(addUserDTO, User.class);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        user.setCreateBy(loginUser.getUser().getId());
        user.setUpdateBy(loginUser.getUser().getId());
        save(user);
        userRoleService.add(user.getId(), addUserDTO.getRoleId());
        return Result.ok("添加成功");
    }
//    public void addUser(){
//        //加密密码
//        String encode = passwordEncoder.encode("123456");
//        User user = User.builder()
//                .userName("admin")
//                .password(encode)
//                .nickName("超级管理员")
//                .email("testuser@example.com")
//                .phoneNumber("13800138000")
//                .status("0")  // 0正常
//                .avatar("https://sky-take-out-0704.oss-cn-hangzhou.aliyuncs.com/2025/07/000a8830-b42a-4377-a164-1ac6afa855bd.png")
//                .delFlag(0)   // 0未删除
//                .sex(1)       // 2未知
//                .userType(1) // 1普通用户
//                .build();
//        save(user);
//    }

    @Override
    public User selectByUserName(String userName) {
        return lambdaQuery().eq(User::getUserName, userName).one();
    }

    /**
     * 分页查询用户信息
     */
    @Override
    public Result<UserListVO> pageList(UserSearchParamsDTO userSearchParamsDTO) {
        // 1. 创建分页对象
        Page<User> page = new Page<>(userSearchParamsDTO.getPage(), userSearchParamsDTO.getLimit());
        // 2. 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 关键字搜索（用户名或昵称）
        if (StrUtil.isNotBlank(userSearchParamsDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like(User::getUserName, userSearchParamsDTO.getKeyword())
                .or()
                .like(User::getNickName, userSearchParamsDTO.getKeyword())
            );
        }
        // 状态筛选
        if (userSearchParamsDTO.getStatus() != null) {
            queryWrapper.eq(User::getStatus, userSearchParamsDTO.getStatus().toString());
        }
        // 时间范围筛选
        if (StrUtil.isNotBlank(userSearchParamsDTO.getStartTime()) && 
            StrUtil.isNotBlank(userSearchParamsDTO.getEndTime())) {
            queryWrapper.between(User::getCreateTime,
                    LocalDate.parse(userSearchParamsDTO.getStartTime()),
                    LocalDate.parse(userSearchParamsDTO.getEndTime())
            );
        }
        // 按创建时间倒序排列
        queryWrapper.orderByDesc(User::getCreateTime);
        // 3. 执行分页查询
        Page<User> userPage = page(page, queryWrapper);
        // 4. 转换为VO对象
        List<PageUserInfoVO> userInfoVOList = userPage.getRecords().stream()
            .map(user -> {
                PageUserInfoVO userInfoVO = new PageUserInfoVO();
                BeanUtil.copyProperties(user, userInfoVO);
                // 处理字段映射
                userInfoVO.setUsername(user.getUserName());
                userInfoVO.setNickname(user.getNickName());
                userInfoVO.setPhone(user.getPhoneNumber());
                userInfoVO.setStatus(user.getStatus().equals("0") ? 0 : 1); // 0正常->0启用, 1停用->1禁用
                
                // 如果需要角色信息，可以在这里查询用户角色
                 Long roleId = userRoleService.getRoleIdByUserId(user.getId());
                 String roleName = roleService.getRoleNameById(roleId);
                 userInfoVO.setRoleId(roleId);
                 userInfoVO.setRoleName(roleName);
                
                return userInfoVO;
            })
            .collect(Collectors.toList());
        
        // 5. 构建返回结果
        UserListVO userListVO = new UserListVO();
        userListVO.setList(userInfoVOList);
        userListVO.setTotal(userPage.getTotal());
        userListVO.setPage((long) userSearchParamsDTO.getPage());
        userListVO.setLimit((long) userSearchParamsDTO.getLimit());
        
        return Result.ok(userListVO);
    }
}
